package com.gxd.web.filter;

import com.gxd.domain.User;
import com.gxd.service.UserService;
import com.gxd.service.impl.UserServiceImpl;
import com.gxd.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class AutoLogin implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        Object user = request.getSession().getAttribute("user");
        if(user!=null){
            filterChain.doFilter(request,response);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if(cookies==null||cookies.length==0){
            response.sendRedirect("/login.jsp");
            filterChain.doFilter(request,response);
            return;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if("autoinfo".equals(name)){
                String value = cookie.getValue();
                String autoinfo = Base64Utils.decode(value);
                String[] split = autoinfo.split("&");
                if(split!=null&&split.length==2){
                    UserService userService = new UserServiceImpl();
                    User login = userService.login(split[0], split[1]);
                    if(login!=null){
                        request.getSession().setAttribute("user",login);
                        response.sendRedirect("/index.jsp");
                        break;
                    }
                }

            }
        }

filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
